package com.javaweb.oa02.web.action;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import java.util.Objects;

public class userSession  implements HttpSessionBindingListener {
    @Override
    public void valueBound(HttpSessionBindingEvent httpSessionBindingEvent) {
        //用户登录，userSession类型对象向session域中存放了,触发监听
        //数量存入域中
        ServletContext application =httpSessionBindingEvent.getSession().getServletContext();
        Object onlineCount = application.getAttribute("onlineCount");

        if(onlineCount==null){
            application.setAttribute("onlineCount",1);
        }else {
           int count=(Integer)onlineCount;
            count++;
            application.setAttribute("onlineCount",count);
        }

    }

    @Override
    public void valueUnbound(HttpSessionBindingEvent httpSessionBindingEvent) {
        //用户退出。userSession类型对象从session域中销毁了
        //数量--存入application应用域
        ServletContext application=httpSessionBindingEvent.getSession().getServletContext();
        Integer count=(Integer)application.getAttribute("onlineCount");
        count--;
        application.setAttribute("onlineCount",count);


    }
    private String username;
    private String password;

    public userSession() {
    }

    public userSession(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        userSession that = (userSession) o;
        return Objects.equals(username, that.username) &&
                Objects.equals(password, that.password);
    }

    @Override
    public int hashCode() {
        return Objects.hash(username, password);
    }

    @Override
    public String toString() {
        return "userSession{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}
